
package dieci.database.supplier;

import dieci.database.PersistentObject;
import dieci.database.SessionFactoryUtil;
import dieci.hibernate.HibSupplier;
import dieci.system.Supplier;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author DuckSys
 */
public class SupplierHibernateDAO implements SupplierDAO
{
    private static Logger logger = Logger.getLogger("SupplierHibernateDAO.log");

    @Override
    public List<Supplier> list()
    {
        List<Supplier> suppliers = new ArrayList<>();

        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            List<HibSupplier> hibSuppliers = session.createCriteria(HibSupplier.class).
                    add(Restrictions.eq("deleted", 0)).addOrder(Order.asc("name")).list();
            for (HibSupplier dbSupplier : hibSuppliers) {
                Supplier supp = new Supplier(dbSupplier.getName(), dbSupplier.getContactPerson(), 
                        dbSupplier.getAddress(), dbSupplier.getEmail(), dbSupplier.getPhone(), 
                        dbSupplier.getWebSite(), dbSupplier.getDeleted());
                supp.setSupplierId(dbSupplier.getSupplierId());
                suppliers.add(supp);
            }

            return suppliers;
        }
        catch (Exception e) {

            logger.log(Level.INFO, "Error listando proveedores", e.getMessage());

            throw new IllegalStateException("Error al listar",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }

    }

    @Override
    public List<Supplier> findBySupplierName(String name)
    {
        List<Supplier> result = new ArrayList<>();
        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            List<HibSupplier> hibSupplier = session.createCriteria(HibSupplier.class).
                    add(Restrictions.eq("deleted", 0)).add(Restrictions.like("name", name + "%")).list();
            for (HibSupplier hibSupplier1 : hibSupplier) {
                if (hibSupplier1 != null) {
                    result.add(new Supplier(hibSupplier1.getSupplierId(), hibSupplier1.getName(), hibSupplier1.getContactPerson(), hibSupplier1.getAddress(),
                            hibSupplier1.getEmail(), hibSupplier1.getPhone(), 
                            hibSupplier1.getWebSite(), hibSupplier1.getDeleted()));

                }
            }
            

        }
        catch (Exception e) {
            throw new IllegalStateException("Error al buscar por nombre",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }

        return result;

    }

    @Override
    public void saveOrUpdate(PersistentObject object)
    {
        Session session = null;

        Supplier supp = (Supplier) object;
        Supplier found = findBySupplierId(supp.getSupplierId());
        try {
            session = SessionFactoryUtil.getInstance().getCurrentSession();
            
            session.beginTransaction();

            if (found != null) 
            {
                //UPDATE
                supp.setSupplierId(found.getSupplierId());
               
                HibSupplier hibSupplier = new HibSupplier(supp.getSupplierId(), (Supplier) supp);
                session.saveOrUpdate(hibSupplier);

            }
            else 
            {
                //NEW
                HibSupplier hibSupplier = new HibSupplier(supp);

                // generate new id for the product
                session.save(hibSupplier);
                
            }

            session.getTransaction().commit();

        }
        catch (Exception e) {
            if(session!=null){
                session.getTransaction().rollback();
            } 
            throw new IllegalStateException("Error al guardar o actualizar",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }
    
    }

    @Override
    public void delete(PersistentObject object)
    {
        Session session = null;

        Supplier supp = (Supplier) object;
        Supplier found = findBySupplierId(supp.getSupplierId());
        try {
            session = SessionFactoryUtil.getInstance().getCurrentSession();
            
            session.beginTransaction();

            if (found != null) 
            {
                //UPDATE
                supp.setSupplierId(found.getSupplierId());
               
                HibSupplier hibSupplier = new HibSupplier(supp.getSupplierId(), (Supplier) supp);
                hibSupplier.setDeleted(1);
                session.saveOrUpdate(hibSupplier);

            }
            
            session.getTransaction().commit();

        }
        catch (Exception e) {
            if(session!=null){
                session.getTransaction().rollback();
            }            
            throw new IllegalStateException("Error al eliminar",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }
    }

    @Override
    public Supplier findBySupplierId(int id)
    {
        Supplier result = null;
        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            HibSupplier hibSupplier = (HibSupplier) session.createCriteria(HibSupplier.class).
                    add(Restrictions.eq("deleted", 0)).add(Restrictions.eq("supplierId", id)).uniqueResult();
            if (hibSupplier != null) {
                result = new Supplier(hibSupplier.getName(), hibSupplier.getContactPerson(), hibSupplier.getAddress(),
                        hibSupplier.getEmail(), hibSupplier.getPhone(), 
                        hibSupplier.getWebSite(), hibSupplier.getDeleted());
                result.setSupplierId(hibSupplier.getSupplierId());
            }

        }
        catch (Exception e) {
            throw new IllegalStateException("Error al buscar por id",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }

        return result;
    }

}
